package response

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/go-sql-driver/mysql"
	"github.com/gookit/event"
	"gorm.io/gorm"
	"net/http"
)

func SucResult(c *gin.Context, httpCode int, dataCode int, msg string, data any) {
	c.JSON(httpCode, gin.H{
		"status": dataCode,
		"msg":    msg,
		"data":   data,
	})
}

func FailResult(c *gin.Context, httpCode int, dataCode int, msg string) {
	c.JSON(httpCode, gin.H{
		"status": dataCode,
		"msg":    msg,
	})
}

// 成功返回
func Success(c *gin.Context, msg string, data any) {
	SucResult(c, http.StatusOK, http.StatusOK, msg, data)
}

// 失败返回
func Fail(c *gin.Context, msg string) {
	FailResult(c, http.StatusOK, http.StatusPreconditionFailed, msg)
}

func FailWithCode(c *gin.Context, httpCode int, msg string) {
	FailResult(c, http.StatusOK, httpCode, msg)
}

func Err(c *gin.Context, err error, msg ...string) {
	switch err.(type) {
	case *mysql.MySQLError:
		event.MustFire("exceptionLogEvent", event.M{
			"errMsg": err.(*mysql.MySQLError).Error(),
			"handle": c,
		})
		FailResult(c, http.StatusInternalServerError, http.StatusInternalServerError, "操作失败")
	default:
		if errors.Is(err, gorm.ErrRecordNotFound) {
			var errMsg string
			if len(msg) > 0 {
				errMsg = msg[0]
			} else {
				errMsg = err.Error()
			}
			FailWithCode(c, http.StatusNotFound, errMsg)
		} else {
			FailWithCode(c, http.StatusPreconditionFailed, err.Error())
		}
	}
}
